package net.j4love.mybatis.kit.plugin;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

/**
 * 数据库分页 SQL 改写器 MySQL 实现
 * @author he peng
 * @date 2018/9/10
 */
public class MySQLPaginationQuerySQLRewriter extends AbstractPaginationQuerySQLRewriter {

    private static final Log LOG = LogFactory.getLog(MySQLPaginationQuerySQLRewriter.class);

    @Override
    public String rewriteSqlForPaging(PaginationQueryInterceptor.Page page, String originalSql) {
        return null;
    }

    @Override
    public String rewriteSqlForCount(String originalSql) {
        String sql = originalSql;
        boolean isSelectSql = StringUtils.startsWithAny(originalSql, "select", "SELECT");
        boolean isCountSql = StringUtils.containsAny(originalSql, "count", "COUNT");
        if (isSelectSql && ! isCountSql) {
            int length = "select".length();
            String selectKeyword = sql.substring(0 , length);
            int formKeywordIndex = StringUtils.indexOfAny(sql, "from", "FROM");
            sql = selectKeyword + " COUNT(*) " + sql.substring(formKeywordIndex);
        }
        return sql;
    }
}
